﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Security;

namespace ObservableUnitTests
{
    [Serializable]
    class CantCreateTempFileException : Exception
    {
        public CantCreateTempFileException():
            base()
        {
        }

        public CantCreateTempFileException(string message) :
            base(message)
        {
        }

        public CantCreateTempFileException(string message, Exception innerException):
            base(message, innerException)
        {
        }
    }

    class TempFile: IDisposable
    {
        private static readonly int MaxTries = 100;        
        private static Random Randomizer = new Random();

        public TempFile()
        {
            for(int i =0; i < MaxTries; i++)
            {
                m_fullPath = Path.GetTempFileName();

                try
                {
                    m_stream = File.Open(m_fullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);                           
                }
                catch (IOException)
                {
                    Trace.TraceInformation("Failed to open for writing temporary file. Try #{0} out of {1}", i, MaxTries);
                }
            }

            if (m_stream == null)
            {
                throw new CantCreateTempFileException("All tries were used but failed to create temporary file.");
            }
        }

        string m_fullPath;
        public string FullPath
        {
            get
            {
                return m_fullPath;
            }
        }

        FileStream m_stream;
        public FileStream Stream
        {
            get
            {
                return m_stream;
            }
        }

        public void Dispose()
        {
            m_stream.Dispose();
            File.Delete(FullPath);
        }

    }
}
